package com.todo.pro.dt.common;

import com.todo.pro.dt.Dt;
import com.todo.pro.dt.client.DtClient;
import com.todo.pro.dt.client.DtClientFactory;
import com.todo.pro.dt.client.DtClientFactoryAware;

/**
 * 所有组件的基类
 * Created by xuan on 2018/8/27.
 */
public class DtBase implements DtClientFactoryAware, DtCloseable {

    /**
     * Client工厂接口
     */
    private DtClientFactory clientFactory;

    /**
     * Client，一般一个组件一个Client
     */
    private DtClient client;

    protected DtClient getClient() {
        if (null == client) {
            initClient();
        }
        return client;
    }

    private void initClient() {
        //如果是空，使用指定工厂初始化
        if (null == client) {
            if (null == clientFactory) {
                this.client = Dt.getInstance().getDefaultDtClientFactory().buildClient();
            } else {
                this.client = clientFactory.buildClient();
            }
        }
    }

    @Override
    public void setClientFactory(DtClientFactory clientFactory) {
        this.clientFactory = clientFactory;
    }

    @Override
    public void close() {
        getClient().close();
    }

}
